//
// Created by fanghr on 17-12-29.
//

#include "Serial.h"

Serial::Serial(boost::asio::io_service & io_service_, std::string device_):serial_port(io_service_) ,device(device_){
    //BOOST_LOG_TRIVIAL(info)<<"Serial port at "<<device<<" constructed.";
    serial_port.open(device);
    serial_port.set_option(boost::asio::serial_port::flow_control());
    serial_port.set_option(boost::asio::serial_port::stop_bits());
    serial_port.set_option(boost::asio::serial_port::character_size(8));
    serial_port.set_option(boost::asio::serial_port::baud_rate(921600));
    set_callback(NULL);
}

Serial::~Serial() {
    stop();
}

void Serial::set_baud_rate(int rate) {
    serial_port.set_option(boost::asio::serial_port::baud_rate(rate));
}

void Serial::run() {
    read_buf();
}

void Serial::stop() {
    serial_port.close();
}

void Serial::read_buf() {
    char *buf=new char[150];
    callback(buf,serial_port.read_some(boost::asio::buffer(buf,150)));
    run();
}

void Serial::set_callback(callback_t cb) {
    callback=cb;
}